<template>
    <div class="smartWarningPlan">
        <a-modal width="90%" :visible="visible" title="预警生产计划" @cancel="modalCancel" class="yuan-modal smartWarningPlan-modal"
            :dialog-style="{ top: '20px' }" :confirm-loading="saveLoading">
            <a-spin tip="Loading..." :spinning="formLoading">
                <div class="yuan-container">
                    <div v-if="!defParentInfo||!defParentInfo.id">
                        <div class="filter-panel">

                            <div class="filter-list">
                                <span>标准：</span>
                                <a-select v-model="pageParams.standard" @change="getParentList" placeholder="请选择标准">
                                    <a-select-option value="1">国标</a-select-option>
                                    <a-select-option value="2">省标</a-select-option>
                                </a-select>
                            </div>
                            <div class="filter-list mast-ico">
                                <span>产品大类：</span>
                                <a-select v-model="pageParams.inventoryType" @change="getParentList" placeholder="请选择大类">
                                    <a-select-option value="C60">C60</a-select-option>
                                    <a-select-option value="C70">C70</a-select-option>
                                    <a-select-option value="C80">C80</a-select-option>
                                    <a-select-option value="C90">C90</a-select-option>
                                </a-select>
                            </div>
                            <div class="filter-list mast-ico">
                                <span>规格：</span>
                                <a-select v-model="pageParams.spec" @change="getParentList" placeholder="请选择规格">
                                    <a-select-option value="大袋">大袋</a-select-option>
                                    <a-select-option value="小袋">小袋</a-select-option>
                                </a-select>
                            </div>
                            <div class="filter-list mast-ico">
                                <span>品名：</span>
                                <a-select v-model="pageParams.parentId" placeholder="请选择品类" show-search
                                    :filter-option="$filterOption">
                                    <a-select-option v-for="item in parentList" :key="item.id"
                                        :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </div>
                            <a-button type="primary" @click="getParentInfo" class="filter-list">确定</a-button>
                        </div>
                    </div>

                    <div class="page-top" v-if="parentInfo&&parentInfo.id">
                        <span class="page-title">{{parentInfo.name}}</span>
                        <span style="margin-left:20px">计划日期：{{nowDate}}</span>
                        <span style="margin-left:20px">产品大类：{{parentInfo.inventoryType}}</span>
                        <span style="margin-left:20px">标准：{{parentInfo.standard}}</span>
                        <span style="margin-left:20px">规格：{{parentInfo.spec}}</span>
                        <a-button type="primary" class="filter-list" style="float:right"
                            @click="showSimulatedPlan">模拟计算</a-button>
                    </div>

                    <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                        :label-col="{ style: { width: '150px' } }" :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }"
                        v-if="parentInfo&&parentInfo.id">
                        <div class="form-panel">
                            <!-- <div class="form-panel-title">{{detailData.varietyName}}</div> -->
                            <div class="form-panel-box">
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="生产计划编号" prop="planSerial">
                                    <a-input class="yuan-form-input" v-model="formData.planSerial"
                                        placeholder="请输入生产计划编号"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col5" label="负责人" prop="personId">

                                    <a-select class="yuan-form-input" v-model="formData.personId" placeholder="请选择"
                                        :filter-option="$filterOption" show-search>
                                        <a-select-option :value="item.userId" v-for="item in accountList"
                                            :key="item.userId">{{item.name}}</a-select-option>
                                    </a-select>
                                </a-form-model-item>
                                <div class="clear-both"></div>
                                <div style="display:flex;width:100%;margin-top:20px">
                                    <div style="flex-grow:1;background-color: #f8f8f8;padding:10px 0">
                                        <div style="margin-bottom:10px">
                                            <span style="margin-left:20px">可供销售天数：{{alarmData.availableSellDay}}天</span>
                                            <span style="margin-left:20px">差量：<span
                                                    class="c-danger font-bignum">{{alarmData.differenceNum}}</span>袋</span>
                                            <span style="margin-left:20px">需求量：{{alarmData.dayRequirement}}袋</span>
                                            <span style="margin-left:20px">成品库存量：{{alarmData.stockNum}}袋</span>
                                        </div>
                                        <template v-if="spec==='大袋'">
                                            <a-form-model-item class="yuan-form-item yuan-form-col5" label="计划包装量"
                                                prop="bigProNum">
                                                <a-input suffix="袋" class="yuan-form-input" v-model="formData.bigProNum"
                                                    placeholder="请输入计划包装量" @input="proNumChange"></a-input>
                                                <span style="margin-left:10px">{{parentInfo.loadingQuantity}} g/袋</span>
                                            </a-form-model-item>
                                            <a-form-model-item class="yuan-form-item yuan-form-col5" label="配方颗粒(颗粒)投入量">
                                                <a-input suffix="kg" class="yuan-form-input" v-model="formData.bigInNum"
                                                    placeholder="请输入" @input="inNumChange"></a-input>
                                            </a-form-model-item>
                                        </template>
                                        <template v-else>
                                            <a-form-model-item class="yuan-form-item yuan-form-col5" label="计划包装量"
                                                prop="smallProNum">
                                                <a-input suffix="袋" class="yuan-form-input" v-model="formData.smallProNum"
                                                    placeholder="请输入计划包装量" @input="proNumChange"></a-input>
                                                <span style="margin-left:10px">{{parentInfo.loadingQuantity}} g/袋</span>
                                            </a-form-model-item>
                                            <a-form-model-item class="yuan-form-item yuan-form-col5" label="配方颗粒(颗粒)投入量">
                                                <a-input suffix="kg" class="yuan-form-input" v-model="formData.smallInNum"
                                                    placeholder="请输入" @input="inNumChange"></a-input>
                                            </a-form-model-item>
                                        </template>
                                    </div>

                                </div>
                                <!-- <div style="display:flex;width:100%;margin-top:20px">
                                    <div style="margin-right:20px;font-size:16px">
                                        规格：大袋
                                    </div>
                                    <div style="flex-grow:1;background-color: #f8f8f8;padding:10px 0">
                                        <div style="margin-bottom:10px">
                                            <span style="margin-left:20px">可供销售天数：{{alarmData.big.availableSellDay}}天</span>
                                            <span style="margin-left:20px">差量：<span
                                                    class="c-danger">{{alarmData.big.differenceNum}}</span>袋</span>
                                            <span style="margin-left:20px">需求量：{{alarmData.big.dayRequirement}}袋</span>
                                            <span style="margin-left:20px">成品库存量：{{alarmData.big.stockNum}}袋</span>
                                        </div>
                                        <a-form-model-item class="yuan-form-item yuan-form-col5" label="计划包装量" prop="bigProNum">
                                            <a-input suffix="袋" class="yuan-form-input" v-model="formData.bigProNum"
                                                placeholder="请输入计划包装量" @input="proNumChange"></a-input>
                                        </a-form-model-item>
                                        <a-form-model-item class="yuan-form-item yuan-form-col5" label="配方颗粒(颗粒)投入量">
                                            <a-input suffix="kg" class="yuan-form-input" v-model="formData.bigInNum"
                                                placeholder="请输入" @input="inNumChange"></a-input>
                                        </a-form-model-item>
                                    </div>

                                </div>
                                <div style="display:flex;width:100%;margin-top:20px">
                                    <div style="margin-right:20px;font-size:16px">
                                        规格：小袋
                                    </div>
                                    <div style="flex-grow:1;background-color: #f8f8f8;padding:10px 0">
                                        <div style="margin-bottom:10px">
                                            <span style="margin-left:20px">可供销售天数：{{alarmData.small.availableSellDay}}天</span>
                                            <span style="margin-left:20px">差量：<span
                                                    class="c-danger">{{alarmData.small.differenceNum}}</span>袋</span>
                                            <span style="margin-left:20px">需求量：{{alarmData.small.dayRequirement}}袋</span>
                                            <span style="margin-left:20px">成品库存量：{{alarmData.small.stockNum}}袋</span>
                                        </div>
                                        <a-form-model-item class="yuan-form-item yuan-form-col5" label="计划包装量" prop="smallProNum">
                                            <a-input suffix="袋" class="yuan-form-input" v-model="formData.smallProNum"
                                                placeholder="请输入计划包装量" @input="proNumChange"></a-input>
                                        </a-form-model-item>
                                        <a-form-model-item class="yuan-form-item yuan-form-col5" label="配方颗粒(颗粒)投入量">
                                            <a-input suffix="kg" class="yuan-form-input" v-model="formData.smallInNum"
                                                placeholder="请输入" @input="inNumChange"></a-input>
                                        </a-form-model-item>
                                    </div>

                                </div> -->

                            </div>
                        </div>
                    </a-form-model>

                    <!-- <div class="form-panel">
                        <div class="form-panel-title">
                            <span>成品详情</span>
                            <a-button type="primary" class="filter-list" style="float:right;margin-left:10px">按图表展示</a-button>
                            <a-button type="primary" class="filter-list" style="float:right">按列表展示</a-button>
                        </div>
                        <div class="form-panel-box">
                            <PlanDetailVue :parentInfo="parentInfo" />
                        </div>
                    </div> -->
                    <PlanListVue ref="planListVue" v-if="planSimulation&&planSimulation.length>0" :planSimulation="planSimulation"
                        :formData="formData" :parentInfo="parentInfo" />
                    <SimulatedPlanVue :visible="simulatedPlanVisible" @closeModal="() => simulatedPlanVisible = false"
                        :bigProNum="formData.bigProNum" :smallProNum="formData.smallProNum" :parentInfo="parentInfo"
                        @simulatedSave="simulatedSave" :spec="spec" />
                    <SureModel :visible="sureVisible" @closeModal="() => sureVisible = false" :sureInfo="sureInfo" @sureClose="sureClose" />
                </div>
            </a-spin>
            <template slot="footer">
                <a-button type="primary" @click="savePlan('1')">
                    保存计划
                </a-button>
                <a-button type="primary" @click="savePlan('2')">
                    保存并分解计划
                </a-button>
                <a-button @click="modalCancel">
                    关闭
                </a-button>
            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import warningApi from "@/api/warningApi";
import { format, toDecimalNoZero } from "@/utils";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import PlanDetailVue from "./planDetial.vue";
import PlanListVue from "./planList.vue";
import SimulatedPlanVue from "./simulatedPlan.vue";
import SureModel from "./sureModel.vue";

@Component({ name: "TPL", components: { PlanListVue, PlanDetailVue, SimulatedPlanVue, SureModel } })
export default class index extends Vue {
    @Prop({ default: "" }) visible!: boolean;
    @Prop({ default: "" }) defSpec!: string;
    @Prop({ default: {} }) defParentInfo!: any; // 父级传入品类信息
    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            // 有父级品类信息 直接进行计算
            if (this.defParentInfo && this.defParentInfo.id) {
                this.spec = this.defSpec + "";
                this.parentInfo = { ...this.defParentInfo };
                this.pageInit();
            } else {
                this.getParentList();
            }

            this.nowDate = format(new Date(), "yyyy年MM月dd号");
        }
    }
    spec = "";
    parentInfo: any = {};
    formLoading = false;
    saveLoading = false;
    nowDate = format(new Date(), "yyyy年MM月dd号");
    formData: any = {
        planSerial: "",
        bigProNum: "",
        smallProNum: "",
        bigInNum: "",
        smallInNum: "",
    };
    rules = {
        planSerial: [{ required: true, message: "请输入生产计划编号", trigger: "change" }],
        bigProNum: [{ required: true, message: "请输入计划包装量", trigger: "change" }],
        smallProNum: [{ required: true, message: "请输入计划包装量", trigger: "change" }],
        personId: [{ required: true, message: "请选择复制人", trigger: "change" }],
    };
    pageParams = {
        name: "",
        inventoryType: undefined,
        spec: "大袋",
        standard: undefined,
        parentId: undefined,
    };
    closeModal() {
        this.formData = {
            plan1: "",
            bigProNum: "",
            smallProNum: "",
            bigInNum: "",
            smallInNum: "",
        };
        setTimeout(() => {
            (this.$refs.form as any).resetFields();
        }, 200);
        this.$emit("closeModal");
    }
    modalCancel() {
        this.closeModal();
    }

    sureVisible = false;
    sureInfo = {};
    savePlan(decomposeState) {
        (this.$refs.form as any).validate(async (valid: any) => {
            if (valid) {
                this.saveLoading = true;
                const processPlanDetailList = (this.$refs["planListVue"] as any).getPageInfo();

                if (processPlanDetailList === false) {
                    this.saveLoading = false;
                    return;
                }
                const validProcessPlanDetailList: any[] = [];
                processPlanDetailList.forEach((item) => {
                    if (Number(item.inputNum) > 0) {
                        validProcessPlanDetailList.push(item);
                    }
                });
                const findUser = this.accountList.find((item: any) => item.userId === this.formData.personId) || { name: "" };
                const data = {
                    decomposeState: decomposeState,
                    availableSellDay: this.alarmData.availableSellDay,
                    person: findUser.name,
                    inventoryType: this.parentInfo.inventoryType,
                    loadingQuantity: this.parentInfo.loadingQuantity,
                    materialId:this.parentInfo.id,
                    materialName: this.parentInfo.name,
                    materialType: this.parentInfo.materialType,
                    planSerial: this.formData.planSerial,

                    prodNum: this.spec === "大袋" ? this.formData.bigProNum : this.formData.smallProNum,
                    spec: this.spec,
                    standard: this.parentInfo.standard,
                    surplus: this.parentInfo.stockNum,
                    processPlanDetailList: validProcessPlanDetailList,
                    type: "成品",

                };
                this.sureVisible = true;
                this.sureInfo = data;
            }
        });
    }
    async pageInit() {
        // 获取负责人列表
        await this.getUserList();
        // 获取成品差量，需求量等基础数据
        await this.getAlarmGetData();
        // 按规格获取大小袋都投入量
        this.proNumChange();
    }
    alarmData: any = {};
    async getAlarmGetData() {
        try {
            this.formLoading = true;
            const res = await warningApi.alarmGetData({ id: this.parentInfo.id });
            const arr = res.data || [];
            const big = arr.find((item) => item.spec === "大袋");
            const small = arr.find((item) => item.spec === "小袋");
            if (this.spec === "大袋") {
                this.alarmData = big || {};
                this.formData.bigProNum = big.differenceNum;
                this.formData.smallProNum = 0;
            } else {
                this.alarmData = small || {};
                this.formData.bigProNum = 0;
                this.formData.smallProNum = small.differenceNum;
            }
        } finally {
            this.formLoading = false;
        }
    }
    specBigRes = {};
    specSmallRes = {};
    async getKeLiNum(bigProNum, smallProNum) {
        try {
            this.formLoading = true;
            const bigRes = await warningApi.getKeLiNum({
                id: this.parentInfo.id,
                num: bigProNum || 0,
                spec: "大袋",
            });
            const smallRes = await warningApi.getKeLiNum({
                id: this.parentInfo.id,
                num: smallProNum || 0,
                spec: "小袋",
            });
            this.specBigRes = bigRes.data;
            this.specSmallRes = smallRes.data;
            return { bigInNum: bigRes.data, smallInNum: smallRes.data };
        } finally {
            this.formLoading = false;
        }
    }

    simulatedPlanVisible = false;
    showSimulatedPlan() {
        this.simulatedPlanVisible = true;
    }
    simulationTimer: number | null = null;
    proNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            const data = await this.getKeLiNum(this.formData.bigProNum, this.formData.smallProNum);
            this.formData.bigInNum = toDecimalNoZero(data.bigInNum);
            this.formData.smallInNum = toDecimalNoZero(data.smallInNum);
            this.reviewPlan();
        }, 500);
    }
    inNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            this.reviewPlan();
        }, 500);
    }
    async reviewPlan() {
        if(this.formData.bigInNum<this.specBigRes || this.formData.smallInNum<this.specSmallRes){
            this.$message.error('颗粒投入量不能小于');
            return
        }
        try {
            this.formLoading = true;
            const res = await warningApi.getKeLiFeeding({
                id: this.parentInfo.materialId,
                num: (Number(this.formData.bigInNum) || 0) + (Number(this.formData.smallInNum) || 0),
            });
            this.planSimulation = res.data.map((item) => {
                const xuqiu = Number(item.num);
                const surplus = Number(item.surplus);
                const inNum = xuqiu > surplus ? xuqiu - surplus : 0;
                return {
                    ...item,
                    xuqiu: toDecimalNoZero(xuqiu),
                    surplus: toDecimalNoZero(surplus),
                    inNum: toDecimalNoZero(inNum),
                };
            });
        } finally {
            this.formLoading = false;
        }
    }
    planSimulation = [];
    accountList = [];
    async getUserList() {
        if (this.accountList && this.accountList.length > 0) return;
        try {
            this.formLoading = true;
            const res = await warningApi.getAccountList({});
            this.accountList = res.data?.rows || [];
        } finally {
            this.formLoading = false;
        }
    }

    simulatedSave(data) {
        this.planSimulation = data.planSimulation;
        this.formData.bigProNum = data.formData.bigNum;
        this.formData.smallProNum = data.formData.smallNum;
        data.planSimulation.forEach((item) => {
            if (item.planName === "包装计划") {
                if (this.spec === "大袋") {
                    this.formData.bigInNum = item.xuqiu;
                    this.specBigRes = item.xuqiu;
                } else {
                    this.formData.smallInNum = item.xuqiu;
                    this.specSmallRes = item.xuqiu;
                }
            }
        });
        // this.formData.bigInNum = toDecimalNoZero(data.bigInNum);
        // this.formData.smallInNum = toDecimalNoZero(data.smallInNum);
    }
    parentList: any[] = [];
    async getParentList() {
        this.parentList = [];
        this.pageParams.parentId = undefined;
        this.parentInfo = {};
        this.planSimulation = [];
        try {
            this.formLoading = true;
            const res = await warningApi.getMaterList({
                materialType: "配方颗粒",
                spec: this.pageParams.spec,
                standard: this.pageParams.standard,
                inventoryType: this.pageParams.inventoryType,
            });
            this.parentList = res.data || [];
        } finally {
            this.formLoading = false;
        }
    }
    getParentInfo() {
        // 父级没有具体品类传入时，根据页面选项获取品类
        const find = this.parentList.find((item) => item.id === this.pageParams.parentId);
        this.parentInfo = find;
        this.spec=find.spec;
        this.pageInit();
    }
    sureClose(){
        this.closeModal()
        this.$emit("resetList");
    }
}
</script>

<style lang="scss">
.smartWarningPlan-modal {
    .page-top {
        padding-bottom: 20px;
        border-bottom: solid 1px #eee;
    }
    .page-title {
        font-weight: bold;
        font-size: 20px;
    }
}
</style>
